package com.lekang.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.system.domain.PendingTasks;
import com.lekang.system.service.IPendingTasksService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;
import java.util.stream.Collectors;

/**
 * 待办任务Controller
 * 
 * @author zihao
 * @date 2025-10-18
 */
@RestController
@RequestMapping("/system/tasks")
public class PendingTasksController extends BaseController
{
    @Autowired
    private IPendingTasksService pendingTasksService;

    /**
     * 查询待办任务列表
     */
    @PreAuthorize("@ss.hasPermi('system:tasks:list')")
    @GetMapping("/list")
    public TableDataInfo list(PendingTasks pendingTasks)
    {
        startPage();
        
        String currentUsername = getUsername();
        System.out.println("=== 待办任务权限检查 ===");
        System.out.println("当前用户: " + currentUsername);
        
        // 护理组组长只查询未处理的任务（处理完的自动从列表中消失）
        if ("hulizuzuzhang".equals(currentUsername)) {
            pendingTasks.setIsHandle(0L); // 只查询未处理的任务
            System.out.println("护理组组长：强制只查询未处理的任务（is_handle=0）");
        }
        
        List<PendingTasks> list = pendingTasksService.selectPendingTasksList(pendingTasks);
        System.out.println("查询到的待办任务总数: " + (list != null ? list.size() : 0));
        
        // 精确权限控制：根据用户角色和任务类型进行过滤
        list = list.stream()
            .filter(task -> {
                // 过滤掉task编号为空的记录
                String taskId = task.getTaskId();
                if (taskId == null || taskId.trim().isEmpty()) {
                    System.out.println("过滤掉task编号为空的任务: ID=" + task.getId());
                    return false;
                }
                
                Long taskType = task.getType();
                
                // 退住申请（type=1）：只有退住审批员a能看
                if (taskType != null && taskType == 1L) {
                    boolean canSee = "tuizhushenpiyuana".equals(currentUsername);
                    System.out.println("退住申请：用户=" + currentUsername + ", 可见=" + canSee);
                    return canSee;
                }
                
                // 请假申请（type=2）：只有护理组组长能看
                if (taskType != null && taskType == 2L) {
                    boolean canSee = "hulizuzuzhang".equals(currentUsername);
                    System.out.println("请假申请：用户=" + currentUsername + ", 可见=" + canSee);
                    return canSee;
                }
                
                // 入住申请（type=3）：护理组组长和护理员都不能看
                if (taskType != null && taskType == 3L) {
                    boolean canSee = !"hulizuzuzhang".equals(currentUsername) && !"huliyuan".equals(currentUsername);
                    System.out.println("入住申请：用户=" + currentUsername + ", 可见=" + canSee);
                    return canSee;
                }
                
                // 其他类型：所有用户都能看
                return true;
            })
            .collect(Collectors.toList());
        
        System.out.println("过滤后的待办任务数量: " + list.size());
        return getDataTable(list);
    }

    /**
     * 导出待办任务列表
     */
    @PreAuthorize("@ss.hasPermi('system:tasks:export')")
    @Log(title = "待办任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PendingTasks pendingTasks)
    {
        List<PendingTasks> list = pendingTasksService.selectPendingTasksList(pendingTasks);
        ExcelUtil<PendingTasks> util = new ExcelUtil<PendingTasks>(PendingTasks.class);
        util.exportExcel(response, list, "待办任务数据");
    }

    /**
     * 获取待办任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:tasks:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pendingTasksService.selectPendingTasksById(id));
    }

    /**
     * 新增待办任务
     */
    @PreAuthorize("@ss.hasPermi('system:tasks:add')")
    @Log(title = "待办任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PendingTasks pendingTasks)
    {
        return toAjax(pendingTasksService.insertPendingTasks(pendingTasks));
    }

    /**
     * 修改待办任务
     */
    @PreAuthorize("@ss.hasPermi('system:tasks:edit')")
    @Log(title = "待办任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PendingTasks pendingTasks)
    {
        return toAjax(pendingTasksService.updatePendingTasks(pendingTasks));
    }

    /**
     * 删除待办任务
     */
    @PreAuthorize("@ss.hasPermi('system:tasks:remove')")
    @Log(title = "待办任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pendingTasksService.deletePendingTasksByIds(ids));
    }

    /**
     * 根据业务ID和步骤号查询待办任务
     */
    @PreAuthorize("@ss.hasPermi('system:tasks:query')")
    @GetMapping("/getByBusinessIdAndStep")
    public AjaxResult getByBusinessIdAndStep(Long businessId, Long stepNo)
    {
        System.out.println("=== 根据业务ID和步骤号查询待办任务 ===");
        System.out.println("业务ID: " + businessId);
        System.out.println("步骤号: " + stepNo);
        
        try {
            PendingTasks queryTask = new PendingTasks();
            queryTask.setBussniessId(businessId);
            queryTask.setStepNo(stepNo);
            queryTask.setIsHandle(0L); // 只查询未处理的任务
            
            List<PendingTasks> tasks = pendingTasksService.selectPendingTasksList(queryTask);
            
            if (tasks != null && !tasks.isEmpty()) {
                PendingTasks task = tasks.get(0); // 取第一个
                System.out.println("✅ 找到待办任务: " + task.getId());
                System.out.println("  任务ID: " + task.getTaskId());
                System.out.println("  步骤号: " + task.getStepNo());
                System.out.println("  状态: " + task.getIsHandle());
                return success(task);
            } else {
                System.out.println("❌ 未找到对应的待办任务");
                return error("未找到对应的待办任务");
            }
        } catch (Exception e) {
            System.err.println("查询待办任务失败: " + e.getMessage());
            e.printStackTrace();
            return error("查询待办任务失败: " + e.getMessage());
        }
    }
}
